import { connect } from 'umi';
import { NeedControllerContext, useNeedReducer } from '../common';
import { Form, Spin, message } from 'antd';
import { getNeedByIDService } from '../services/DetailOAService';
import { DetailInfoTopViewOA } from './DetailInfoTopViewOA';
import { DetailInfoCenterViewOA } from './DetailInfoCenterViewOA';
import { DetailInfoBottomViewOA } from './DetailInfoBottomViewOA';
import { useEffect, useMemo, useState } from 'react';
import { getColorTextLoadMap, getPosIDs, getUserID, renderWaterMarkDom } from '@/utils';
import '../common/style.less';
import { NeedManageAPI } from '../common/type';
import { NeedUpdateService } from '../services/UpdateService';
import { purchaseNeedCategory } from '../common/Format';
import { setOAMessageSev } from '../../Acommon';

const DetailInfoViewOA: React.FC<NeedManageAPI.INeedDetailInfoView> = ({ curRes, locationProps }) => {
  /** 表单 */
  const [needForm] = Form.useForm();

  /** 样式根名称 */
  const prefix = 'need-update-';

  /** 获取reducets */
  const { needDispatch, tableData } = useNeedReducer();

  /** 保存原需求信息 */
  const [saveOldNeedInfo, setSaveOldNeedInfo] = useState<Record<string, any>>({});

  /** 消息已读已办接口 */
  const { setOAMessageRun, setOAMessageLoaidng } = setOAMessageSev(() => {});

  /** 详情回调 */
  const detailsCallback = (res: any) => {
    if (res && res?.msgFlag) {
      // 做已读办理的接口处理
      let infoObject = res?.obj;
      if (infoObject && infoObject?.paramObject?.[purchaseNeedCategory()]) {
        let workFlowNode = infoObject?.paramObject?.[purchaseNeedCategory()];
        if (
          workFlowNode &&
          workFlowNode?.mactivitiTaskList?.length > 0 &&
          workFlowNode?.mactivitiTaskList?.[0]?.assigneePositionID == getPosIDs() &&
          workFlowNode?.mactivitiTaskList?.[0]?.assigneeID == getUserID()
        ) {
          setOAMessageRun({
            // 已读未办
            id: locationProps?.state?.taskId,
            isRemark: 0,
            viewType: 1,
          });
        }
      }
    } else {
      message.error(res?.msg);
    }
  };

  // 初始化水印
  // useEffect(() => {
  //   renderWaterMarkDom('needOAPage-divBox', true);
  //   return () => {
  //     renderWaterMarkDom('needOAPage-divBox', false);
  //   };
  // }, []);

  /** 获取详情 */
  const { getNeedByIDRun, getNeedByIDLoading, getNeedByIDInfo, reloadDetailInfo } = getNeedByIDService(detailsCallback);

  /** API 接口 */
  const { editNeedService } = NeedUpdateService();

  /** 编辑接口 */
  const { editNeedRun, editNeedLoading } = editNeedService();

  /** 编辑需求 */
  const fetchEditNeed = async (params: Record<string, any>) => {
    const { msgFlag } = await editNeedRun(params);
    if (msgFlag) {
      reloadDetailInfo();
    }
  };

  /** 初始化 */
  useEffect(() => {
    if (locationProps?.state?.pageInfo?.id) {
      getNeedByIDRun({ id: locationProps?.state?.pageInfo?.id });
    }
  }, [locationProps?.state?.id]);

  /** 是否可以办理流程 */
  const nodesFlowListMemo = useMemo(() => {
    let infoObject = {
      ...getNeedByIDInfo,
      supplyTypeName: getColorTextLoadMap(getNeedByIDInfo?.supplyTypeName)?.colorText,
      procureRealName: getColorTextLoadMap(getNeedByIDInfo?.procureRealName)?.colorText,
    };
    const taskHandInfo: Record<string, any> = infoObject?.paramObject?.[purchaseNeedCategory()];
    if (
      taskHandInfo &&
      taskHandInfo?.mactivitiTaskList?.length > 0 &&
      taskHandInfo?.mactivitiTaskList?.[0]?.assigneePositionID == getPosIDs() &&
      taskHandInfo?.mactivitiTaskList?.[0]?.assigneeID == getUserID()
    ) {
      return taskHandInfo?.mactivitiTaskList?.[0];
    } else {
      return false;
    }
    // return true // [演示]
  }, [getNeedByIDInfo?.paramObject]);

  /** 已审核，待审核，总数 */
  const NumGatherMemo = useMemo(() => {
    let resObj = {
      yiNum: 0,
      daiNum: 0,
      allNum: tableData?.length || 0,
    };

    let num = 0;
    tableData?.forEach((item: Record<string, any>) => {
      if (!item?.checkState) {
        num += 1;
      }
    });
    resObj.daiNum = num;
    resObj.yiNum = resObj?.allNum - num;
    return resObj;
  }, [tableData, getNeedByIDInfo]);

  return (
    <NeedControllerContext.Provider
      value={{
        styleFixCls: prefix,
        curRes,
        locationID: locationProps?.state?.id,
        needDispatch,
        pageType: locationProps?.state?.pageType,
        oldNeedInfo: {
          ...saveOldNeedInfo,
        },
        needForm,
        reloadDetail: reloadDetailInfo,
        needDetailInfo: {
          ...getNeedByIDInfo,
          supplyTypeName: getColorTextLoadMap(getNeedByIDInfo?.supplyTypeName)?.colorText,
          procureRealName: getColorTextLoadMap(getNeedByIDInfo?.procureRealName)?.colorText,
        },
        tableData,
        fetchEditNeed,
        nodesFlowListMemo,
        NumGatherMemo,
        setOAMessageRun,
        taskId: locationProps?.state?.taskId,
      }}
    >
      <Spin spinning={getNeedByIDLoading || editNeedLoading || setOAMessageLoaidng}>
        <div className={`${prefix}infoViewOA`} id={'needOAPage-divBox'}>
          <DetailInfoTopViewOA />
          <DetailInfoCenterViewOA />
          <DetailInfoBottomViewOA />
        </div>
      </Spin>
    </NeedControllerContext.Provider>
  );
};

export default connect(({ baseLogin }: Record<string, any>) => ({
  curRes: baseLogin?.permissions,
}))(DetailInfoViewOA);
